//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by Albert Zhu on 16/10/12.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 通过webView加载登录注册界面
class WBOAuthViewController: UIViewController, UIWebViewDelegate {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        super.loadView()
        view = webView
        view.backgroundColor = UIColor.white
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill), isBack: false)
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载授权页面
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedictURL)"
        
        webView.loadRequest(URLRequest(url: URL(string: url)!))
    }
    
    @objc func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc func autoFill() {
        // 准备js
        let js = "document.getElementById('userId').value = 'albertzhutr@sina.cn';" + "document.getElementById('passwd').value = '13515541659';"
        //让webView执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }
    
    //MARK: - UIWebViewDelegate
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if !((request.url?.absoluteString.hasPrefix(WBRedictURL))!){
            return true
        }
        
        debugPrint("加载请求-------\(request.url?.absoluteString)")
        debugPrint("加载请求-------\(request.url?.query)")
        
        if !(request.url?.query?.hasPrefix("code="))! {
            debugPrint("取消授权")
            
            return false
        }
        
        let query = request.url!.query!
        
        let accessToken = query.substring(from: "code=".endIndex)
    
        WBNetworkManager.shared.loadAccessToken(code: accessToken) { (isSuccess) in
            if isSuccess {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSucceedNotification), object: nil)
                
                self.close()
            } else {
                SVProgressHUD.showInfo(withStatus: "授权失败")
            }
        }
        
        debugPrint("获取授权码-----\(accessToken)")
 
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
